<script setup lang="ts" name="Operlog">
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { checkPermission } from '@/utils/permission'
import { getDicts } from '@/api/system/dict/index'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { downloadBlobFile, warnBox } from '@/utils'
import { cleanOperlog, delOperlog, list, operlogExport } from '@/api/system/operlog/index'
import type { OperLog, QueryParams } from '@/api/system/operlog/type'
import { ElMessage } from 'element-plus'
import ViewDialog from './components/ViewDialog.vue'

// form
const formValue = ref<QueryParams & { daterange?: string[] }>({
	operIp: '',
	title: '',
	operName: '',
	businessType: '',
	status: '',
	daterange: []
})

const sysOperType = ref<IGetDictsRes>([])
const sysCommonStatus = ref<IGetDictsRes>([])

const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '操作地址',
		prop: 'operIp'
	},
	{
		type: 'input',
		label: '系统模块',
		prop: 'title'
	},
	{
		type: 'input',
		label: '操作人员',
		prop: 'operName'
	},
	{
		type: 'select',
		label: '操作类型',
		prop: 'businessType',
		options: sysOperType as unknown as any,
		attrs: {
			style: {
				width: '200px'
			}
		}
	},
	{
		type: 'select',
		label: '操作状态',
		prop: 'status',
		options: sysCommonStatus as unknown as any,
		attrs: {
			style: {
				width: '200px'
			}
		}
	},
	{
		type: 'date-picker',
		label: '操作时间',
		prop: 'daterange',
		attrs: {
			type: 'datetimerange',
			'range-separator': '至',
			'start-placeholder': '开始日期',
			'end-placeholder': '结束日期',
			'value-format': 'YYYY-MM-DD HH:mm:ss',
			'default-time': [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
		}
	}
])

// table
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})
const tableData = ref<OperLog[]>([])
const selectionList = ref<OperLog[]>([])

const columns = ref<TableColums[]>([
	{
		type: 'selection',
		width: 50
	},
	{
		type: 'index',
		label: '序号',
		align: 'center',
		width: 60
	},
	{
		label: '日志编号',
		prop: 'id'
	},
	{
		label: '系统模块',
		prop: 'title'
	},
	{
		label: '操作类型',
		prop: 'businessType'
	},
	{
		label: '操作人员',
		prop: 'operName'
	},
	{
		label: '操作地址',
		prop: 'operIp'
	},
	{
		label: '操作状态',
		prop: 'status'
	},
	{
		label: '操作日期',
		prop: 'createTime',
		width: 160
	},
	{
		label: '消耗时间',
		prop: 'costTime'
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: 100,
		align: 'center'
	}
])

const multiple = computed(() => !(selectionList.value.length >= 1))

const getTableData = async () => {
	loading.value = true

	const params = {
		pageNum: page.value.currentPage,
		pageSize: page.value.pageSize,
		...formValue.value,
		'params[beginTime]': formValue.value.daterange?.[0],
		'params[endTime]': formValue.value.daterange?.[1]
	}
	delete params.daterange

	const res = await list(params)
	tableData.value = res.data.rows
	page.value.total = res.data.total
	loading.value = false
}

// 弹窗
const viewDialogRef = useTemplateRef('viewDialogRef')

const handleView = (row: OperLog) => {
	viewDialogRef.value?.init(row)
}

const handleDeleteBatch = async () => {
	if (selectionList.value.length === 0) return

	const ids = selectionList.value.map(item => item.id).join(',')
	await warnBox({
		message: `是否确认删除选中的${selectionList.value.length}条数据？`
	})

	try {
		await delOperlog(ids)
		ElMessage.success('删除成功')
		getTableData()
	} catch (error) {
		console.error('删除失败:', error)
		ElMessage.error('删除失败，请重试')
	}
}

const handleClean = async () => {
	await warnBox({
		message: '是否确认清空所有操作日志数据项？'
	})

	try {
		await cleanOperlog()
		ElMessage.success('清空成功')
		getTableData()
	} catch (error) {
		console.error('清空失败:', error)
		ElMessage.error('清空失败，请重试')
	}
}

const handleExport = async () => {
	try {
		const params = {
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			...formValue.value,
			'params[beginTime]': formValue.value.daterange?.[0],
			'params[endTime]': formValue.value.daterange?.[1]
		}
		delete params.daterange

		const data = await operlogExport(params)
		downloadBlobFile(data.data, data.filename || `operlog_${new Date().getTime()}.xlsx`)
	} catch (error) {
		console.error('导出失败:', error)
		ElMessage.error('导出失败，请重试')
	}
}

const selectionChange = (selection: OperLog[]) => {
	selectionList.value = selection
}

const init = () => {
	getDicts('sys_sys_oper_type').then(data => {
		sysOperType.value = data
	})
	getDicts('sys_sys_common_status').then(data => {
		sysCommonStatus.value = data
	})
}

onMounted(() => {
	init()
	getTableData()
})
</script>

<template>
	<div class="table-page-box">
		<div class="filter-box">
			<QForm
				inline
				:model="formValue"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="getTableData"
			/>
		</div>
		<div class="table-box">
			<QTable
				:data="tableData"
				:columns="columns"
				:page="page"
				:loading="loading"
				style="width: 100%"
				@pageChange="getTableData"
				@selectionChange="selectionChange"
			>
				<template #headerLeft>
					<el-button
						v-if="checkPermission(['monitor:operlog:remove'])"
						type="danger"
						:disabled="multiple"
						@click="handleDeleteBatch"
					>
						删除
					</el-button>
					<el-button
						v-if="checkPermission(['monitor:operlog:remove'])"
						@click="handleClean"
					>
						清空
					</el-button>
					<el-button
						v-if="checkPermission(['monitor:operlog:export'])"
						@click="handleExport"
					>
						导出
					</el-button>
				</template>
				<template #businessType="{ row }">
					<DictTag
						:options="sysOperType"
						:value="row.businessType"
					/>
				</template>
				<template #status="{ row }">
					<DictTag
						:options="sysCommonStatus"
						:value="row.status"
					/>
				</template>
				<template #action="{ row }">
					<el-button
						v-if="checkPermission(['monitor:operlog:query'])"
						type="primary"
						link
						@click="handleView(row)"
					>
						详细
					</el-button>
				</template>
			</QTable>
		</div>
		<ViewDialog ref="viewDialogRef" />
	</div>
</template>
